<template>
  <div>
    <el-card shadow="hover">
      <template #header>
        <el-button type="primary" icon="ele-Plus" @click="dialog()"
          >添加</el-button
        >
      </template>
      <el-table :data="trademarks">
        <el-table-column
          width="100"
          label="序号"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row }">
            <img :src="row.logoUrl" width="100" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row }">
            <el-button
              type="warning"
              icon="ele-Edit"
              size="small"
              @click="dialog(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              icon="ele-Delete"
              size="small"
              @click="deleteTrade(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 
        page-size:每页显示条目个数
       -->
      <el-pagination
        :total="total"
        :page-size="pagesize"
        :current-page="page"
        :page-sizes="[5, 10, 15]"
        layout="prev,pager,next,jumper,->,sizes,total"
        @current-change="currentChangeHandler"
        @size-change="sizeChangeHandler"
      ></el-pagination>
    </el-card>
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="formData" ref="formRef" :rules="rules">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="formData.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 
              el-upload: 
                action:必选参数，上传的地址
                show-file-list:是否显示已上传文件列表
                on-success:文件上传成功时的钩子
             -->
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="onSuccessUpload"
          >
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar"
            />
            <el-icon class="avatar-uploader-icon" v-if="!formData.logoUrl"
              ><ele-Plus
            /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureToAddOrEditTrade"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "ProductTradeMarkListIndex",
});
</script>

<script lang="ts" setup>
import { ref, nextTick } from "vue";
import {
  requestTrademarkListByPage,
  requestSaveBaseTrademark,
  requestUpdateTrademark,
  requestDeleteTrademark,
} from "@/api/trademark";
import type {
  typeRecord,
  addBaseTrademark,
  updateBaseTrademark,
} from "@/api/trademark";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadFile, UploadFiles, FormRules } from "element-plus";
//初始化数据
const trademarks = ref<typeRecord[]>([]); //请求品牌信息列表
const pagesize = ref(3); //每页显示条目个数
const total = ref(0); //总条目数
const page = ref(1); //当前页
const formRef = ref();
const dialogVisible = ref(false); //对话框显示隐藏
const formData = ref<addBaseTrademark | updateBaseTrademark>({
  tmName: "",
  logoUrl: "",
}); //添加品牌表单数据
const dialogTitle = ref(""); //对话框标题
const uploadUrl = ref(`${import.meta.env.VITE_API_URL}/product/upload`);
//表单校验规则
const rules: FormRules = {
  tmName: [
    {
      required: true,
      min: 1,
      max: 20,
      message: "品牌名称必须是1-20个字符之间",
      trigger: "blur", //失焦时触发校验
    },
  ],
  logoUrl: [
    {
      required: true,
      // 自定义验证的函数
      validator(rule: any, value: string, callback) {
        // console.log("当前的value", value);
        if (value === "") {
          // 调用callback表示当前验证结束，callback中传入值表示有错误，不传入任何值，表示验证成功
          callback("品牌LOGO必填");
        } else {
          const ext = value.substring(value.lastIndexOf(".") + 1);
          // console.log(ext);
          if (!["png", "jpg", "gif"].includes(ext)) {
            callback("品牌LOGO必须是图片");
          } else {
            callback();
          }
        }
      },
      // message: "品牌LOGO必填",
      trigger: "blur", //失焦时触发校验
    },
  ],
};
//初始化1:请求分页数据
async function getTradeMarks() {
  try {
    const result = await requestTrademarkListByPage(page.value, pagesize.value);
    console.log(result, "请求分页数据");
    trademarks.value = result.records;
    total.value = result.total;
    page.value = result.current;
    pagesize.value = result.size;
  } catch (e) {}
}
getTradeMarks();
//事件1:当前页改变触发
function currentChangeHandler(v: number) {
  page.value = v;
  getTradeMarks();
}
//事件2:每页条数
function sizeChangeHandler(v: number) {
  pagesize.value = v;
  getTradeMarks();
}
//事件3:添加按钮/编辑按钮点击事件
const dialog = (row?: typeRecord) => {
  console.log("事件3:row", row);
  dialogVisible.value = true;
  if (row) {
    //有row则是编辑逻辑
    //使用本行的数据(含id),需要使用浅拷贝
    formData.value = { ...row };
    dialogTitle.value = "编辑品牌";
  } else {
    //无row是添加逻辑
    //清空上一次的数据
    formData.value.tmName = "";
    formData.value.logoUrl = "";
    dialogTitle.value = "添加品牌";
  }
  nextTick(() => {
    formRef.value?.clearValidate(); //清理某个字段的表单验证信息
  });
};
//事件4:文件上传成功时的钩子  参数1：上传返回值  参数2：当前上传的文件的信息(代理对象)  参数3：已经上传的全部文件组成的数组（代理对象）
const onSuccessUpload = (
  response: { code: number; data: string },
  file: UploadFile,
  fileList: UploadFiles
) => {
  console.log(response, file, fileList);
  if (response.code == 200) {
    formData.value.logoUrl = response.data;
  }
};
//事件5:确定添加品牌 按钮
const sureToAddOrEditTrade = async () => {
  try {
    // 调用 formRef.value.validate() 方法来对这个表单中指定的数据（model、rules）进行校验
    try {
      //校验
      const res = await formRef.value.validate();
      console.log("校验成功", res);

      //dialog隐藏
      dialogVisible.value = false;
      if (dialogTitle.value === "添加品牌") {
        console.log("添加");
        //添加品牌请求
        await requestSaveBaseTrademark(formData.value);
        //弹出添加成功
        ElMessage.success("添加成功");
        //改变当前页
        page.value = Math.ceil((total.value + 1) / pagesize.value);
      } else {
        console.log("修改");
        //编辑品牌请求
        await requestUpdateTrademark(formData.value as updateBaseTrademark);
      }

      //重新请求当页数据
      getTradeMarks();
    } catch (e) {
      console.log("校验失败", e);
    }
  } catch (e) {
    ElMessage.error("添加失败");
  }
};
//事件6:删除按钮 事件
const deleteTrade = async (row: typeRecord) => {
  console.log("事件6", row);
  try {
    // ElMessageBox 是一个异步的，因为要等待用户操作后才返回结果，ElMessageBox可以通过回调，
    //也可以通过promise来获取到用户操作后的结果
    await ElMessageBox({
      title: "提示",
      message: "你确定要删除吗？",
      icon: "ele-Delete",
    });
    await requestDeleteTrademark(row.id);
    page.value = Math.floor((total.value - 1) / pagesize.value);
    getTradeMarks();
  } catch (e) {
    ElMessage.error("删除失败");
  }
};
</script>

<style lang="less" scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
